<template>
  <div class="app-container">
    <div style="padding: 20px;">
      <el-form>
        <el-form-item v-if="stores && stores.length > 1" label="采购仓库">
          <el-select v-model="toStore" filterable>
            <el-option
              v-for="item in stores"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采购产品">
          <el-select v-model="choosedProduct" filterable placeholder="请选择需要申购的产品" @change="chooseProduct">
            <el-option
              v-for="item in products"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申购列表">
          <div>
            <el-table
              :data="productList"
              style="width: 100%"
            >
              <el-table-column
                type="index"
                width="50"
              />
              <el-table-column
                prop="name"
                label="产品"
                width="250"
              />
              <el-table-column
                prop="quantity"
                label="申购数量"
                width="250"
              >
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.quantity" :min="1" />
                </template>
              </el-table-column>
              <el-table-column
                prop=""
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="deleteList(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item label="采购备注">
          <el-input v-model="comment" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      id: Number(this.$route.params.id),
      store: '',
      products: [],
      productList: [],
      choosedProduct: '',
      comment: '',
      toStore: '',
      stores: []
    }
  },
  created() {
    this.store = localStorage.getItem('storeId')
    // 先查门店的所有可销售产品
    this.axios.get(`/api/stores/${this.store}`).then((res) => {
      console.log(res.data)
      const myStore = res.data
      // 如果是门店的，搜索仓库，并且将采购订单绑定仓库，方便仓库,仓库的搜索条件就是同一个区域的
      if (res.data.category.id === 1) {
        // 如果多个仓库，就需要选择，一个，就不需要选择
        let filter = `entity.getStatus() == 0 && entity.getId() != ${myStore.id} && entity.getCategory().getId() == 2`
        if (myStore.region) {
          filter += ` && entity.getRegion().getId() == ${myStore.region.id}`
        }
        this.axios.get(`/public/stores`, {
          params: {
            '@filter': filter
          }
        }).then((res) => {
          if (res.data && res.data.length > 0) {
            this.stores = res.data
            this.toStore = res.data[0].id
          }
        })
      }
      this.axios.get(`/api/specifications`, { params: {
        '@filter': `entity.getProduct().getCategory().getParent().getParent().getId() == ${res.data.category.id} && entity.getProduct().getIsOnSale()`,
        '@display': "['id','name']",
        limit: 1000
      }}).then((res) => {
        this.products = res.data
        console.log(this.products)
      })
    })
    if (this.id) {
      this.disabled = true
      // if (this.store > 0) {
      //   this.axios.get(`/store/${this.store}/officers/${this.id}`, { params: {
      //     '@expands': `['entity.user']`
      //   }}).then((res) => {
      //     this.form.userId = res.data.user.id
      //     this.form.type = res.data.type
      //     this.form.username = res.data.user.__metadata.username
      //     this.form.enabled = res.data.enabled
      //   })
      // }
    }
  },
  methods: {
    chooseProduct(e) {
      console.log(e)
      // 先判断有无已经选择了
      for (const i of this.productList) {
        if (i.id == e) {
          this.$message.error('产品已经选择了，不需要重复选择！')
          return
        }
      }
      for (const i of this.products) {
        if (i.id == e) {
          this.productList.push({
            id: i.id,
            name: i.name,
            quantity: 1
          })
          return
        }
      }
    },
    deleteList(id) {
      console.log(id)
      // 删除记录
      for (const i in this.productList) {
        if (this.productList[i].id == id) {
          this.productList.splice(i, 1)
          return
        }
      }
    },
    submit() {
      if (this.productList.length == 0) {
        this.$message.error('请先选择采购的产品！')
        return
      }
      const items = []
      for (const i of this.productList) {
        items.push({
          specification: i.id,
          quantity: i.quantity,
          primeCost: 0
        })
      }
      const purchase = {
        comment: this.comment,
        items: items
      }
      if (this.toStore !== '' && this.toStore > 0) {
        purchase['toStore'] = this.toStore
      }
      this.axios.post(`/store/${this.store}/purchases`, purchase).then((res) => {
        this.$message.success('创建成功')
        this.$router.push(`/store-purchase/list`)
      })
    }
  }
}
</script>
